#!/bin/sh

set -e

die()
{
  echo $@ >&2
  exit 1
}

usage()
{
  die "Usage: $0 [--sr=<sr>] <iso>"
}

. /etc/xensource-inventory

while [ -n "$1" ]; do
  case "$1" in
    --sr=*)
      sr_uuid=${1#--sr=};;
    -*)
      usage;;
    *)
      break;;

  esac
  shift
done

iso="$1"
[ -n "$iso" ] || usage

function clean_up {
  set +e
  xe update-pool-clean uuid=$update_uuid
  hosts=$(xe update-param-get param-name=hosts uuid=$update_uuid)
  [ -z "$hosts" ] && xe update-destroy uuid=$update_uuid
  set -e
}

update_uuid=$(xe update-upload file-name="$iso" ${sr_uuid:+sr-uuid=$sr_uuid})
trap clean_up ERR
xe update-apply uuid=$update_uuid host=$INSTALLATION_UUID
xe update-pool-clean uuid=$update_uuid
